<template>
  <view class="viewport theme-light">
    <uv-navbar title="" placeholder bgColor="transparent" leftIcon="" :autoBack="false">
      <template #left>
        称重列表
      </template>
    </uv-navbar>

    <uv-sticky class="tabs">
      <!--  :lineColor="themeColor"
      :activeStyle="{ color: themeColor }"
      :current="curTab" :list="tabs"
          @click="onTabChange" -->
      <view class="tabs-container">
        <view class="tabs">
          <view v-for="item in tabs" :key="item.index" class="tab-item" :class="{ 'active': item.index === curTab }"
            @tap="onTabChange(item)">
            {{ item.name }}
          </view>
        </view>
      </view>
    </uv-sticky>

    <view class="container">
      <view class="tab_contents">
        <view class="tabs_search" @tap="openModal">
          <image src="../../static/images/detail/Vector-2.png" style="width: 14px; height: 14px;"></image>
        </view>
        <view class="tabs_totals">
          <view class="tabs_totals_item">总车次:{{ summary.count }}</view>
          <view class="tabs_totals_item">总净重:{{ summary.jz }}</view>
          <view class="tabs_totals_item">总金额:{{ summary.je }}</view>
        </view>
      </view>

      <!-- list_components -->
      <TabListComponents :items="pagedRecordList.rows" @detail="toDetail"></TabListComponents>

    </view>
    <KeyboardPlate ref="plateNumberIns" safeArea @change="plateKeyboardCfg.onPlateChange" isShow>
    </KeyboardPlate>
    <uv-popup ref="popupIns" :close-on-click-overlay="true" mode="center">
      <view class="p-4">
        <uv-form labelWidth="auto" :model="dynamicSearch">
          <block v-for="item in formFields" :key="item.key">
            <uv-form-item v-if="['Input', 'AutoComplete'].includes(item.formType)" :label="item.value" :prop="item.key"
              @click="plateKeyboardCfg.open(item.key)">
              <uv-input v-if="item.key === 'Ch'" v-model="dynamicSearch[item.key]" disabled disabledColor="#ffffff"
                part="">
                <template #suffix>
                  <uv-icon name="keyboard" customPrefix="aj-icon" size="24"></uv-icon>
                </template>
              </uv-input>
              <uv-input v-else v-model="dynamicSearch[item.key]">
              </uv-input>
            </uv-form-item>
            <uv-form-item v-if="item.formType == 'InputTextArea'" :label="item.value" :prop="item.key">
              <uv-textarea v-model="dynamicSearch[item.key]" :autoHeight="true">
              </uv-textarea>
            </uv-form-item>

            <uv-form-item v-if="item.formType == 'Checkbox'" label=" " :prop="item.key">
              <uv-checkbox-group v-model="dynamicSearch[item.key]" placement="row">
                <uv-checkbox :label="item.value" :name="item.value"></uv-checkbox>
              </uv-checkbox-group>
            </uv-form-item>
            <uv-form-item v-if="item.formType == 'CheckboxGroup'" :label="item.value" :prop="item.key">
              <uv-checkbox-group v-model="dynamicSearch[item.key]" placement="column" iconPlacement="right"
                style="flex: 1;">
                <uv-checkbox class="py-3 uv-border-bottom" :label="co.label" v-for="co in item.children" :key="co.value"
                  :name="co.label"></uv-checkbox>
              </uv-checkbox-group>
            </uv-form-item>
            <uv-form-item v-if="item.formType == 'RadioGroup'" :label="item.value" :prop="item.key">
              <uv-radio-group v-model="dynamicSearch[item.key]" placement="column" iconPlacement="right"
                style="flex: 1;">
                <uv-radio class="py-3 uv-border-bottom" :label="co.label" :name="co.label" v-for="co in item.children"
                  :key="co.value"></uv-radio>
              </uv-radio-group>
            </uv-form-item>
            <uv-form-item v-if="item.formType == 'Select'" :label="item.value" :prop="item.key"
              @click="showPicker(item)">
              <uv-input v-model="dynamicSearch[item.key]" disabled disabledColor="#ffffff" border="none"></uv-input>
              <template #right>
                <uv-icon name="arrow-right"></uv-icon>
              </template>
            </uv-form-item>
            <uv-form-item v-if="item.formType == 'DatePicker'" :label="item.value" :prop="item.key"
              @click="showDatePicker(item)">
              <uv-input v-model="dynamicSearch[item.key]" disabled disabledColor="#ffffff" border="none"></uv-input>
              <template #right>
                <uv-icon name="arrow-right"></uv-icon>
              </template>
            </uv-form-item>

          </block>
          <uv-form-item label="开始日期" prop="EntryTimeStart" @click="showDatePicker({ key: 'EntryTimeStart' })">
            <uv-input v-model="dynamicSearch.EntryTimeStart" disabled disabledColor="#ffffff" border="none"></uv-input>
            <template #right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item label="结束日期" prop="EntryTimeEnd" @click="showDatePicker({ key: 'EntryTimeEnd' })">
            <uv-input v-model="dynamicSearch.EntryTimeEnd" disabled disabledColor="#ffffff" border="none"></uv-input>
            <template #right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-button shape="circle" type="primary" text="搜索" @tap="onSearch"></uv-button>

        </uv-form>
      </view>

    </uv-popup>
    <uv-picker ref="pickerIns" :defaultIndex="picker.defaultIndex" :columns="picker.columns" @confirm="pickerConfirm"
      @cancel="pickerCancel">
    </uv-picker>
    <uv-datetime-picker ref="datePickerIns" v-model="datePicker.value" :mode="datePicker.mode"
      @confirm="datePickerConfirm" @cancel="datePickerCancel">
    </uv-datetime-picker>

  </view>
</template>

<script setup lang="ts">
import { ref, computed, toRaw, unref, reactive } from 'vue'
import { getMemberProfileAPI } from '@/services/profile'
import { onShow, onReachBottom, onLoad } from '@dcloudio/uni-app'
import { useMemberStore, useTenantSystemStore, usePoundStore } from '@/stores'
import { themeColor } from '@/utils/index';
import { TableNameEnum, CURDOperationEnum } from '@/enums/tableCurdEnum'
import mqttStatus, { on as mqttOn, MQTTEvent, connect, getPoundFields, tableCurd, getMainApplication } from '@/utils/mqtt';
import dayjs from 'dayjs'
import KeyboardPlate from '@/components/keyboard-plate/index.vue'
import TabListComponents from '@/components/tab-list-components/record.vue'
const memberStore = useMemberStore()
const systemStore = useTenantSystemStore()
const poundStore = usePoundStore()

const popupIns = ref()

const pickerIns = ref()
const picker = reactive({
  show: false,
  columns: [],
  defaultIndex: [],
  current: null,
})

const datePickerIns = ref()
const datePicker = reactive({
  show: false,
  current: null,
  value: '',
  mode: 'date'
})


const listLoading = ref('loading')
const loading = ref(true)

const formFields = ref([])

/// 弹窗键盘输入
const plateNumberIns = ref()
const plateKeyboardCfg = reactive({
  visible: false,
  open: (type) => {

    if (type === 'Ch') {
      plateNumberIns.value.open()
    }
  },
  onPlateChange: ({ value }) => {
    dynamicSearch.value.Ch = value
    // formIns.value.validateField('Ch')
  }
})

const onSearch = () => {
  closePopup()
  searchForm.page = 1
  getList()
}

const datePickerCancel = () => {

}
const datePickerConfirm = (e) => {
  dynamicSearch.value[datePicker.current.key] = dayjs(e.value).format('YYYY-MM-DD')
}
const showDatePicker = (item) => {
  uni.hideKeyboard()
  datePicker.mode = item.componentProps && item.componentProps.showTime ? 'datetime' : 'date'
  datePicker.current = item
  datePicker.value = dynamicSearch.value[item.key]
  datePickerIns.value.open()
}
const pickerCancel = () => {

}
const pickerConfirm = (e) => {
  dynamicSearch.value[picker.current.key] = e.value[0]
}
const showPicker = (item) => {
  uni.hideKeyboard()
  const array = item.children.map(p => p.label)
  const curVal = dynamicSearch.value[item.key]
  picker.current = item
  picker.columns = [array]
  picker.defaultIndex = [array.findIndex(p => p == curVal)]
  pickerIns.value.open()
}

const closePopup = () => {
  popupIns.value.close()
}

const searchForm = reactive({
  page: 1,
  limit: 10,
})

const dynamicSearch = ref({
  EntryTimeStart: '',
  EntryTimeEnd: ''
})

const pagedRecordList = reactive({
  hasNextPage: true,
  totalItemCount: 0,
  rows: []
})

const tabs = reactive([{
  type: 'all',
  name: '全部',
  index: 0,
  searchHandle: () => {
    dynamicSearch.value.IsFinish = null
    dynamicSearch.value.By20 = false
  }
}, {
  type: '0',
  name: '未完成',
  index: 1,
  searchHandle: () => {
    dynamicSearch.value.IsFinish = false
    dynamicSearch.value.By20 = false
  }
}, {
  type: '1',
  name: '已完成',
  index: 2,
  searchHandle: () => {
    dynamicSearch.value.IsFinish = true
    dynamicSearch.value.By20 = false
  }
},
])
const curTab = ref(0)

const openModal = () => {
  popupIns.value.open()
}

/// 去详情页
const toDetail = (item) => {
  uni.navigateTo({
    url: `/pagesData/detail?id=${item.AutoNo}`,
    events: {
      'updated': () => {
        onTabChange(tabs[curTab.value])
      }
    },
    success: ({ eventChannel }) => {
      eventChannel.emit('init', { ...toRaw(unref(item)) })
    },
  })
}

const onMQTTConnected = () => {

  getPoundFields(null, ({ Success, Message, Body }) => {
    if (!Success) {

      uni.showModal({
        title: '错误',
        content: `获取磅单字段失败:${Message}`,
        showCancel: false,
      })
      return;
    }
    const { fields } = Body;
    formFields.value = fields
    poundStore.setFields(fields)
    fields.filter(p => p.key != 'EntryTime').forEach(p => {
      dynamicSearch.value[p.key] = ''
    });

    getList()

  })

}

onLoad(() => {
  if (!mqttStatus.online) {
    mqttOn(MQTTEvent.Connect, onMQTTConnected)
  }
})

onReachBottom(() => {
  if (!pagedRecordList.hasNextPage) {
    return
  }
  searchForm.page++
  getList()
})

const summary = ref({
  count: 0,
  jz: 0,
  je: 0

})

const processList = ({ Success, Message, Body }) => {
  if (!Success) {
    uni.showModal({
      title: '错误',
      content: `获取数据失败:${Message}`,
      showCancel: false,
    })
  } else {
    const { rows, hasNextPage } = Body
    listLoading.value = hasNextPage ? 'loadmore' : 'nomore'
    pagedRecordList.hasNextPage = hasNextPage
    if (searchForm.page == 1) {
      pagedRecordList.rows = rows

    } else {
      pagedRecordList.rows = [...pagedRecordList.rows, ...rows]

    }
    getSummary()

  }

  setTimeout(() => {
    loading.value = false
  }, 1000)
  uni.stopPullDownRefresh()
}

const getSummary = () => {
  const filter = { ...toRaw(unref(dynamicSearch.value)) }
  tableCurd({
    tableName: TableNameEnum.WeighingRecord,
    operation: CURDOperationEnum.Summary,
    body: {
      ...searchForm,
      ...filter
    }
  }, ({ Success, Message, Body }) => {

    if (!Success) {
      uni.showModal({
        title: '错误',
        content: `获取统计数据失败:${Message}`,
        showCancel: false,
      })
      return
    }

    summary.value = Body
  })
}

const getList = () => {
  if (!memberStore.profile) {
    return
  }
  const handler = tabs.find(p => p.index == curTab.value)
  if (handler) {
    handler.searchHandle()
  }
  listLoading.value = 'loading'
  const filter = { ...toRaw(unref(dynamicSearch.value)) }

  tableCurd({
    tableName: TableNameEnum.WeighingRecord,
    operation: CURDOperationEnum.Query,
    body: {
      ...searchForm,
      ...filter
    }
  }, processList)

}

const onTabChange = ({ index, searchHandle }) => {
  searchForm.limit = 10
  curTab.value = index
  searchForm.page = 1
  getList()
}

onShow(() => {
  if (memberStore.profile && memberStore.detailProfile.selectedActiveCode) {
    if (mqttStatus.online) {
      onMQTTConnected()
    } else {
      uni.showModal({
        title: '提示',
        content: '云服务已离线,请前去主页连接后重试',
      })
    }

  }
})

</script>

<style scoped lang="scss">
@import "@/styles/aj_custom/index.scss";

.tabs-container {
  display: flex;
  justify-content: center;
  font-size: 14px;
  margin-top: 25px;

  .tabs {
    display: flex;

    .tab-item {
      padding: 6px 22px;
      margin-right: 10px;
      cursor: pointer;
    }
  }

  .tab-item.active {
    background-color: rgba(26, 102, 255, 1);
    border-radius: 178px;
    color: white;
  }
}

.tab_contents {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  margin: 13px 15px;

  .tabs_search,
  .tabs_totals {
    box-shadow: 5px 5px 25px rgba(0, 0, 0, 0.1);
    background-color: white;
    padding: 10px;
    border-radius: 10px;
  }

  .tabs_totals {
    margin-left: 5px;
    display: flex;
    flex: 1;
    justify-content: space-between;
  }
}

.popup_content_container {
  position: relative;

  .popup_content_masker {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 998;
    width: 100%;
    height: 100%;
    background-color: rgba(166, 166, 166, 0.32);
    padding: 20px;
  }

  .popup_content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 999;
    width: 96%;

    .popup_content_detail {
      padding: 25px 20px;
      background-color: white;
      border-radius: 5px;
      margin-bottom: 20px;

      .order_notice_content {
        display: flex;
        justify-content: space-between;

        .order_notice_detail {
          font-size: 12px;
          // padding: 25px 10px 5px 10px;
          border-bottom: 1px solid #f2f2f2;

          .order_notice_detail_input {
            border: none;
          }
        }
      }
    }

    .popup_search {
      // display: inline-block;
      color: white;
      text-align: center;
      background-color: rgba(26, 102, 255, 1);
      padding: 12px 66px;
      border-radius: 25px;
    }
  }
}

uv-input .uv-border {
  border-color: transparent !important;
}
</style>
